package edu.chl.jadetalk.business;

import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.ejb.Stateless;

/**
 * This bean implements the functionality declared in MailerBeanLocal
 * @author jesper
 */
@Stateless
public class MailerBean implements MailerBeanLocal {

    @Override
    public boolean sendMail(String user, String passwd, String from, String to, 
    String subject, String content, String host, int port) {

        try {
            // Create mail session
            Properties props = new Properties();
            props.put("mail.transport.protocol", "smtps");
            props.put("mail.smtps.host", host);
            props.put("mail.smtps.auth", "true");

            Session mailSession = Session.getDefaultInstance(props);
            mailSession.setDebug(true);

            // Create message
            MimeMessage message = new MimeMessage(mailSession);
            message.setSubject(subject);
            message.setSender(new InternetAddress(from));
            message.setContent(content, "text/plain");
            message.addRecipient(Message.RecipientType.TO, 
                    new InternetAddress(to));

            Transport t = mailSession.getTransport();
            t.connect(host, port, user, passwd);
            t.sendMessage(message, message.getRecipients
                    (Message.RecipientType.TO));
            t.close();
            return true;
        } catch (MessagingException e) {
            Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE,
                            "Error trying to send email.");
            return false;
        }
    }

    @Override
    public boolean sendMail(String address, String title, String message) {
        //Dummy method
        return true;
    }
}
